package com.prodavalnik.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.prodavalnik.exceptions.UserAlreadyExistOnDBException;
import com.prodavalnik.model.DataBaseController;
import com.prodavalnik.model.User;

/**
 * Servlet implementation class RegistrationLogin
 */
@WebServlet("/RegistrationLogin")
public class RegistrationLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistrationLogin() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
		String username = request.getParameter("name");
		String password = request.getParameter("password");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		
		PrintWriter writer = response.getWriter();
		
		try {
			if(DataBaseController.returnUserByUsernameAndPassword(username, password)!=null){
				writer.print("User already exist");
			}
			else{
				if(User.checkPassword(password)){
					DataBaseController.addUser(username, password, email,phone+","+address);
					writer.print("Successfully register");
				}
				else{
					writer.print("Password must contain at least eight characters,  one Uppercase letter , one Lowercase letter and one digit !");
				}
		}
		} catch (SQLException | UserAlreadyExistOnDBException e) {
			e.printStackTrace();
		}
		
	}

}
